125. Valid Palindrome
Description
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s, return true if it is a palindrome, or false otherwise.
info
You can read the full description here.
Solution
Approach
- Filter characters. Remove characters except for alphabets or numbers.
re.sub
is a good choice.
- Compare strings or lists.
Implementation
class Solution:
def isPalindrome(self, s: str) -> bool:
res = []
# O(N)
for letter in s:
if (letter.isalnum()):
res.append(letter.lower())
# Slicing is O(1), list comparision is O(N)
return res == res[::-1]
Complexity Analysis
- : number of characters in sentence
s
) - Time Complexity :
- Space Complexit :